var tgd = tgd || {};
tgd.Contests = tgd.Contests || {};
tgd.Contests.Darts = tgd.Contests.Darts || {};

tgd.Contests.Darts.RandomSolutionFactory = function (numDarts, numRegions, maxRegion) {

	this._numDarts = numDarts;
	this._numRegions = numRegions + 1;  //implicit 0
	this._maxRegionValue = maxRegion
	this._regions = [];
	this._first = true;
	this._callbacks = [];
	this._running = false;

	for (var i = 0; i < this._numRegions; this._regions[i] = i++);

	if (tgd.Contests.Darts.RandomSolutionFactory._initialized === undefined) {

		tgd.Contests.Darts.RandomSolutionFactory.prototype.next = function() {
			if (!this._first) {
				for (var i = 2; i < this._numRegions; ++i) {
					//todo: update this to be a little smarter, if possible
					this._regions[i] = Math.floor(((Math.random() * 10000) % this._maxRegionValue) + 2);

					//this._regions[i] = (Math.floor(Math.random() * 10000) % (this._numDarts * (i - 1))) + this._regions[i - 1] + 1;

					//var rrr = Math.floor(Math.random() * 6);
					//this._regions[i] = this._regions[i - 1] + rrr + 1;
				}
			}
			this._first = false;
			return new tgd.Contests.Darts.Solution(this._numDarts, this._regions);
		}

		tgd.Contests.Darts.RandomSolutionFactory.prototype.registerCallback = function(c) {
			this._callbacks.push(c);
		}

		tgd.Contests.Darts.RandomSolutionFactory.prototype.start = function() {
			var self = this;

			if (!this._running) {
				this._running = true;
				var runTimer = function() {
					var t = self.next();
					for (var i = 0; i < self._callbacks.length; ++i) {
						self._callbacks[i](t);
					}
					if (self._running) {
						setTimeout(runTimer, 8);
					}
				};
				setTimeout(runTimer, 512);
			}
		}

		tgd.Contests.Darts.RandomSolutionFactory.prototype.stop = function() {
			this._running = false;
		}

		tgd.Contests.Darts.RandomSolutionFactory._initialized = true;
	}
};